package com.hqyj.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * 自动填充
 * 通过反射获取到实体对象，然后对实体对象中的字段进行填充
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        Object goodsJoinTime = getFieldValByName("goods_join_time",metaObject);
        if (null == goodsJoinTime){
            setFieldValByName("goodsJoinTime",MyMetaObjectHandler.date(),metaObject);
        }

        Object saleGoodsTime = getFieldValByName("sale_goods_time",metaObject);
        if (null == saleGoodsTime){
            setFieldValByName("saleGoodsTime",MyMetaObjectHandler.date(),metaObject);
        }

        Object suppliersStartTime = getFieldValByName("suppliers_start_time",metaObject);
        if (null == suppliersStartTime){
            setFieldValByName("suppliersStartTime",MyMetaObjectHandler.date(),metaObject);
        }

        Object suppliersEndTime = getFieldValByName("suppliers_end_time",metaObject);
        if (null == suppliersEndTime){
            setFieldValByName("suppliersEndTime",MyMetaObjectHandler.tenDate(MyMetaObjectHandler.date()),metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {}

    public static String date(){
        Date date = new Date();
        String format = "yyyy-MM-dd";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        return simpleDateFormat.format(date);
    }

    public static String tenDate(String s){
        String s1 = s.substring(0,4);
        String s2 = s.substring(4);
        int i = Integer.valueOf(s1)+ 5;
        return i + s2;
    }
}
